﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SU.Center.Domain.SY;
using SU.Center.Infa;

namespace SU.Center.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AddImageController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly QiniuUtils _qiniuUtils;
        private readonly IBaseReposiotry<PictureInfo> _pictureInfoRepository;
        public AddImageController(IMediator mediator, QiniuUtils qiniuUtils, IBaseReposiotry<PictureInfo> pictureInfoRepository)
        {
            _mediator = mediator;
            _qiniuUtils = qiniuUtils;
            _pictureInfoRepository = pictureInfoRepository;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UploadFile(IFormFile file)
        {
            // 校验文件是否为空
            if (file.Length == 0)
            {
                return BadRequest("未选择文件");
            }
            // 生成文件保存名称
            string name = DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetFileName(file.FileName);

            // 使用 MemoryStream 读取文件数据
            using (var stream = new MemoryStream())
            {
                file.CopyTo(stream);
                byte[] data = stream.ToArray();

                // 调用上传方法
                try
                {
                    var response = _qiniuUtils.UploadFile(data, name);
                    return Ok(response);
                }
                catch (Exception ex)
                {
                    // 捕获上传异常并返回错误信息
                    return StatusCode(500, $"文件上传失败: {ex.Message}");
                }
            }
        }
    }
}
